package com.cuixichang.minimalism.core.oauth2.enhancer;

import cn.hutool.json.JSONUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 自定义token信息
 */
@Component
public class CustomTokenEnhancer  implements TokenEnhancer {
    private static final Log logfactory = LogFactory.get();
    @Autowired
    private ObjectMapper objectMapper;
    // 过滤掉密码等敏感信息
    private static final List<String> filteredKeys = Arrays.asList("password","authorities","accountNonExpired","accountNonLocked","credentialsNonExpired","enabled");
    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken oAuth2AccessToken, OAuth2Authentication oAuth2Authentication) {
        Object principal = oAuth2Authentication.getPrincipal();
        try {
            String jsonstring = objectMapper.writeValueAsString(principal);
            if(logfactory.isDebugEnabled()){
                logfactory.debug("TokenEnhancer {0}",jsonstring);
            }
            Map<String,Object> allowFilteredInfo = objectMapper.readValue(jsonstring, new TypeReference<Map<String,Object>>(){});
            filteredKeys.stream().forEach(key->allowFilteredInfo.remove(key));
            // 获取登录信息并过滤敏感信息后添加到自定义信息
            ((DefaultOAuth2AccessToken)oAuth2AccessToken).setAdditionalInformation(allowFilteredInfo);
        }catch (Exception e){
            logfactory.error(e);
        }
        return oAuth2AccessToken;
    }
}
